<?php
/**
 * @filesource modules/block/controllers/IndexController.php
 * @author Tran Van Hoang
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 *   - bulk
 *   - translate
 *   TODO: google maps data points for all the districts, cities -> DB
 */ 
 
class Block_IndexController extends Clu_Controller_Action_Hvn
{
	public $m; //model

	public function init()
	{
		$this->m = new Model_Block();
		parent::init();
	}

    protected function _moduleChange($moduleName)
    {
        $this->getLayout()->setLayoutPath(
            dirname(dirname(
                $this->getLayout()->getLayoutPath()
            ))
            . DIRECTORY_SEPARATOR . $moduleName . '/views/layouts'
        );
        $this->getLayout()->setLayout($moduleName);
    }
	
    private function getTemplate ($t, $incomingRequest)
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$module = $t[0];
    	$controller = $t[1];
    	$action = $t[2];
    	/* NO need to check permission, this is already checked withthe hvn plugin
    	if (strpos($sess->userPermissions, 'administer everything') && 
    		($module == 'category' || $module == 'block' || $module == 'user'))
    	{
    		return 'admin';
    	}
		*/
		/*
    	if (in_array($module, array('category','block')))
    	{
    		return 'onecol';
    	}
    	*/
    	/*
    	if ($module == 'user' && $controller == 'account' && ($action == "personal-details" || $action == "avatar" || $action == "change-pass" || $action == "upgrade-account"))
    		return 'onecol';
    	*/
    	/*
    	if ($action == 'search')
    		return 'admin';
    	*/
    	//some special incomingRequest;
    	$config = array (
    		/*"home/index/index" => "home",*/
    		"hvn/index/home" => "index",
    		"gome/index/index" => "gome",
    		"gome/index/news" => "gome",
    		"gome/index/list-news" => "gome",
    		/*place*/
    		"place/index/home" => "place",
    		"place/index/view" => "place",
    		"place/index/new" => "place",
    		"place/index/edit" => "place",
    		"place/index/edit-basic" => "place",
    		"place/index/search" => "place",
    		"place/index/travel-info" => "place",
    		/*event*/
    		"event/index/home" => "event",
    		"event/index/view" => "event",
    		"event/index/new" => "event",
    		"event/index/edit" => "event",
    		"event/index/search" => "event",
    		"event/index/gallery" => "event",
    		/*Tour*/
    		"tour/index/home" => "tour",
    		"tour/index/new" => "tour",
    		"tour/index/edit" => "tour",
    		"tour/index/new-tleg" => "tour",
    		"tour/index/view" => "tour",
    		"tour/index/search" => "tour",
    		"tour/index/new-tleg" => "tour",
    		"tour/index/gallery" => "tour",
    		"tour/index/list-tleg" => "tour",
    		/*news*/
    		"news/index/new" => "place",
    		"news/index/search" => "place",
    		/*article*/
    	   /*
    		"article/index/new" => "place",
    		"article/index/search" => "place",
			*/
    		"article/index/new" => "gome",
    		"article/index/search" => "gome",
    		"article/index/edit" => "gome",
    		"article/index/translate" => "gome",
    	
    	/*user*/
    		"user/account/login" => "user",
    		"user/account/personal-details" => "user",
    		"user/account/logout" => "index",
    		"user/account/billing-info" => "user",
    		"user/account/change-account-type" => "user",
    		"user/account/change-pass" => "user",
    		"user/account/upgrade-account" => "user",
    		"user/account/register" => "user",
    		"user/account/view" => "user",
    		"user/account/avatar" => "user",
    		/*block*/
    		"block/index/search" => "user",
    		"block/index/edit" => "user",
    		"block/index/view" => "user",
    		"comment/index/edit" => "place",
    	);
    	if (isset($config[$incomingRequest]))
    		return $config[$incomingRequest];
    	else
    		return 'index';
    }
	/**
	 * Always called for any page. 
	 * That is why the setLayout() is moved from Hvn Plugin's preDispatch() to here	
	 */ 
	public function finalAction() 
    {
    	$layout = Zend_Layout::getMvcInstance();
		$sess = new Zend_Session_Namespace(CLU_NS);
    	$theme = isset($sess->userTheme) ? $sess->userTheme:Zend_Registry::get('configuration')->general->defaultTheme;
    	$layout->setLayoutPath( APP_PATH . '/public/themes/'.$theme.'/layouts/scripts');
    	//TODO: depending on different request, set different template here
		//get the original request name here:
		$incomingRequest = $sess->incomingRequest;
		
		$t = explode('/', $incomingRequest);
    	$template = $this->getTemplate($t, $incomingRequest);
        $layout->setLayout ($template); //common.phtml
		
        //common blocks. Always render
        $this->renderToHolder('index/language.phtml', false, null, 2, 2); //box 1, weight 1 (top menu)
        $this->view->currentController = $t[1];
        if($t['0'] == 'hvn')
			$this->renderToHolder('index/menu.phtml', false, null, 2, 1); //box 1, weight 1 (top menu)
		else if($t['0'] == 'place' && $t['2'] != 'travel-info')
			$this->renderToHolder('index/menu-place.phtml', false, null, 2, 1); 
		else if($t['0'] == 'event')
			$this->renderToHolder('index/menu-event.phtml', false, null, 2, 1); 
		else if($t['0'] == 'tour')
			$this->renderToHolder('index/menu-tour.phtml', false, null, 2, 1); 
		else if($t['2'] == 'travel-info')
			$this->renderToHolder('index/menu-tourism-guide.phtml', false, null, 2, 1);
//		else if($t['0'] == 'user' || $t['0'] == 'article' || $t['0'] == 'news' || $t['0'] == 'block')
//			$this->renderToHolder('index/menu.phtml', false, null, 2, 1);  
        //getting the blocks is divided into 2 steps:
        //1. Get the block list that is stored in session
        //this involves a search query info: roles, lang, theme(userTheme), owner
        //2. Filter to get a smaller set of block list from session
        //this involves: modules,positions(depending on template)
        
        //STEP 1: session data
//		unset($sess->blockList);
        if (!isset($sess->blockList))
        {
			$sData = array();
			//TODO: get $sess->userTheme, $sess->viewLang, $sess->roles, $sess->permissions,
			$auth = Zend_Auth::getInstance();
			
			$sData['theme'] = $theme;
			$sData['roles'] = $sess->userRoles;
			$sData['language'] = $sess->viewLang;
			
			if ($auth->hasIdentity())
				$sData['owner'] = $auth->getIdentity()->id;
				
			$sess->blockList = $this->m->searchBlockList($sData);
        }	
        //STEP 2: filtering		
		//now filter only the allowed blocks from the session blocks
		//
		$blocks = array();
		foreach ($sess->blockList  as $b)
		{
			$tmp = explode("/",$incomingRequest);
			$origModuleName = $tmp[0];
			
			if (strpos($b['modules'], $origModuleName) === false && strpos($b['modules'], 'all') === false)
			{
				continue;
			}
			
			//{theme:template:region:weight}. For example: {prime:common:4:1}
			$matches = array();
			$pattern = "/{".$theme.":".$template.":(\d+):(\d+)}/";
			//just get the first match, because there *MUST* be only one $weight + region for a pair of (theme, template0
			preg_match ($pattern, $b['positions'], $matches);
			if (count($matches) > 0)	
			{
				$b['region'] = $matches[1];
				$b['weight'] = $matches[2];
			}
			else
			{
//				echo "no matched potisions for " . $b['name'];
				continue;
			}
			//add the satisfied blocks to the list of found blocks
			//find region&weight from here as well
			$blocks[] = $b;
//			echo "matched block: " . $b['name'] . "<br/>";
		}
//		echo "<hr/>";
//		echo "Now adding the blocks <hr/>";
		//now the add blocks
		
        foreach ($blocks as $b)
        {
        	//get the weight & region from
        	$weight = $b['weight'] ? $b['weight'] : 2;
        	$region = $b['region'] ? $b['region'] : 5;
        	if (!empty($b['action_url']))// it's an action
        	{
        		$a = explode ('/', $b['action_url']);
				$miniReq = array(
        			'module' => $a[1],
					'controller' => $a[2],
					'action' =>  $a[3],
					'theme' => $theme,
					'template' => $template,
					'regionId' => $region,
					'boxWeight' => $weight
        		);
        		$this->addMiniAction($miniReq);

//        		$this->_helper->actionStack($a[3], $a[2], $a[1], array('lang'=>$sess->viewLang, 'theme'=>$theme, 'template'=>$template));
        	}
        	else if (!empty($b['text']))
        	{
        		$this->setHolder($b['text'], $region, $weight);
        	}
        	
        }
    }
    
    public function newAction()
    {
    	//TODO: if both action_url & body_text are not null, then errors
    	$this->view->form = new Form_NewBlock();
    	$this->view->form->cluBuild(array('action' => 'new'));
    	if ($this->_request->isPost() && $this->view->form->isValid($_POST)) 
        {
        	$data = $this->_request->getParams();
            $this->m->insertRaw($data, false);
            $lastInsertId = $this->db->lastInsertId();
            //forward to avoid refreshing
            $this->_forward("success", 'index' , 'block', array('lastInsertId' => $lastInsertId, 'lang' => 'en' ) );
            return;
        }
        	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
    	$this->renderToHolder('index/new.phtml', false, null, 4, 1);
    }
    
    public function viewAction()
    {
    	$id = $this->_request->getParam("id");
    	if (!$b = $this->m->findByPrimary($id))
        {
            $this->view->errorMessage = __('Cannot find the requested block');
            $this->renderToHolder('common/error.phtml');
            return;
        }
        $this->view->b = $b;
        
        	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
    	$this->renderToHolder('index/view.phtml',false, null, 4, 1);
    }
    


	public function editAction()
	{
    	$id = $this->_request->getParam("id");

    	if (!$b = $this->m->getBlockData($id))
        {                
            $this->view->errorMessage = __('Cannot find the requested block');
            $this->renderToHolder('common/error.phtml');
            return;
        }
	
        //everything's fine. Continue editing
        $form = new Form_NewBlock();
    	$form->cluBuild(array('action' => 'edit'));
        
        //populate the data with 
		if (!$this->_request->isPost())
		{
			$formData = $b->toArray();
			$positions = explode(':',$formData['positions']);
		    $formData['languages'] = explode(',', $b['languages']);
		    $formData['themes'] = explode(',', $b['themes']);
		    $formData['roles'] = explode(',', $b['roles']);
		    $formData['modules'] = explode(',', $b['modules']);
		    if(isset($positions['1']))
		    	$positions['1'] = $positions['1'];
		    else
		    	$positions['1'] = null;
		    if(isset($positions['4']))
		    	$positions['4'] = $positions['4'];
		    else
		    	$positions['4'] = null;
		    if(isset($positions['7']))
		    	$positions['7'] = $positions['7'];
		    else
		    	$positions['7'] = null;
		    if(isset($positions['10']))
		    	$positions['10'] = $positions['10'];
		    else
		    	$positions['10'] = null;
			$a = array($positions['1'], $positions['4'], $positions['7'], $positions['10']);
			$formData['template'] = $a;
			$formData['region'] = $positions['2'];
			$formData['weight'] = substr($positions['3'], 0, 1);
            $form->populateForm($formData);
		}
        else if ($form->isValid($_POST))
        {	
            if ($this->m->saveRaw($b, $form->getValues(), $id, false))
            {
                $this->view->operation = __("update block");
                $this->renderToHolder('common/success.phtml');
                return;
            }
            else 
                $this->view->errorMessage = __("Could not update block to DB");
        }
        else 
        	$this->view->errorMessage = __("Input is not valid");

        $this->view->form = $form;
        $this->view->id = $id;
        	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
        $this->renderToHolder('index/edit.phtml', false, null, 4, 1);    
	}
        
    public function deleteAction()
    {
    	if (!$id = $this->_request->getParam('id'))
    	{
    		$this->view->errorMessage = __('No block id specified');
    		$this->renderToHolder('common/error.phtml');
            return;
        }
        
        if ($this->m->deleteByPrimary(array($id)))
        {
            $this->view->operation = __("Delete block");
            $this->renderToHolder('common/success.phtml');
        }
		else
		{   
			$this->view->errorMessage = __('Could not delete from DB');
            $this->renderToHolder('common/error.phtml');
		}   
    }	
    
	public function searchAction()
	{
		//unset($_SESSION['paginator']);
    	$data = $this->_request->getParams();
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$form = new Form_Search();
    	
		if (strpos($sess->userPermissions, "administer place"))
			$cluSearchMode = "fullAdminSearch";
	    else
			$cluSearchMode = "fullSearch";
				    
        $form->cluBuild(array('action' => 'search', 'view' => $this->view, 'cluSearchMode' => $cluSearchMode));

        //if ($this->_request->isPost())
        if (isset($data['clu_search']) || $this->_request->isPost())
        {
	        //place list + pagination
	       	if (!isset($data['block_perpage']))
    			$data['block_perpage'] = 10;
    		if (!isset($data['page']))
    			$data['page'] = 1;
    			
		   	$select = $this->m->search($data);
			$paginator = $this->generatePaginator($select, $data['page'], $data['block_perpage'], 7, 'Jumping');
			$form->populateForm($data);
			
	       	//cache in $_SESSION
	       	$sess = new Zend_Session_Namespace("paginator");
	       	$sess->block_admin = array("search_params" => $data);
        }
        else
        {
			if (!empty($data['page']) )
	        {
	           $sess = new Zend_Session_Namespace("paginator");
	           $data = $sess->block_admin;
	           if(isset($data))
	           {
           			$select = $this->m->search($data['search_params']);
           			$paginator = $this->generatePaginator($select, $this->_getParam('page'), $data['search_params']['block_perpage'], 
           													7, 'Jumping');
					$form->populateForm($data['search_params']);
	           }
	        }
        }
        
       //the search form, with populated data if any
		$this->view->form = $form; 
			$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		$this->renderToHolder('index/search.phtml', false, null, 4, 1);	
		//$this->renderToHolder('index/'.$cluSearchMode . '.phtml');
       
       //the results
       if(isset($paginator))
       {	
	       	$this->view->paginator = $paginator;
	       	$roleList = $this->m->getRoleName($paginator->getCurrentItems());
	       	$this->view->blockList = $roleList;
			$t = $this->_request->getParam('page');
			$pageNum  = !empty($t) ? $t : 1; 
			$perPage = isset($data['block_perpage']) ? $data['block_perpage']:  $data['search_params']['block_perpage'];
			$this->view->startIndex = $perPage * ($pageNum - 1);
			$this->view->numberOfItems = $paginator->getTotalItemCount();
			$this->view->perPage = $perPage;
			$this->view->pageNum = $pageNum;
			$this->view->numberOfPages = ceil($this->view->numberOfItems/$this->view->perPage);  
	       	//$this->renderToHolder('index/list_admin.phtml');
	       	$this->renderToHolder('index/list.phtml', false, null, 4,2);
       }
	}
    
     public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
		$paginator->setItemCountPerPage($itemsPerPage);
		$paginator->setCurrentPageNumber($pageNumber);
		$paginator->setPageRange($pageRange);
		Zend_Paginator::setDefaultScrollingStyle($style);
		return $paginator;
    }
    
    public function successAction()
    {
         $this->view->blockId =  $this->_request->getParam("lastInsertId");
         $this->renderToHolder('index/postSuccess.phtml');  
    }
    
    public function indexAction()
    {
    	$this->setHolder('helloworld');
    }
}
?>
